package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 保存地址
     * @param addressBook
     */
    @Transactional
    @Override
    public void saveAddressBook(AddressBook addressBook) {
        //为传来的地址对象填充值
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.DISABLE);
        //添加入库
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询地址列表
     * @param userId
     * @return
     */
    @Override
    public List<AddressBook> queryByUserId(Long userId) {
        //查询当前用户下的地址，并返回
        return addressBookMapper.queryByUserId(userId);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook queryById(Long id) {
        //根据id查询地址，并返回
        return addressBookMapper.queryById(id);
    }

    /**
     * 更新地址
     * @param addressBook
     */
    @Override
    public void updateByAddressBook(AddressBook addressBook) {
        //更新地址
        addressBookMapper.updateByAddressBook(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //根据id删除地址
        addressBookMapper.deleteById(id);
    }

    /**
     * 更新默认地址
     * @param addressBook
     */
    @Transactional
    @Override
    public void updateDefaultAddress(AddressBook addressBook) {
        //查询当前是否已有默认地址
        AddressBook book = addressBookMapper.queryByUserIdWithIsDefault(BaseContext.getCurrentId(), StatusConstant.ENABLE);
        //判断是否有默认地址
        if (!ObjectUtils.isEmpty(book)){
            //关闭默认地址
            book.setIsDefault(StatusConstant.DISABLE);
            //更新默认地址
            addressBookMapper.updateByAddressBook(book);
        }
        //将当前传来的地址设置为默认地址
        addressBook.setIsDefault(StatusConstant.ENABLE);
        //更新默认地址
        addressBookMapper.updateByAddressBook(addressBook);
    }

    /**
     * 查询默认地址
     * @param userId
     * @return
     */
    @Override
    public AddressBook queryDefaultAddress(Long userId) {
        //查询默认地址，并返回
        return addressBookMapper.queryByUserIdWithIsDefault(userId, StatusConstant.ENABLE);
    }
}
